package com.sali.asyncollection.controller.asyn_request_merge;

import cn.hutool.json.JSONObject;
import com.sali.asyncollection.model.SysUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @description:  测试异步请求合并
 * @author: sali
 * @date: 2024/7/25 上午7:52.
 * @version: 1.0
 */
@RequestMapping("/admin/v1")
@RestController
@Slf4j
public class UserController {

    private ExecutorService executorService = Executors.newCachedThreadPool();

    @GetMapping("/user/info1")
    public JSONObject getUserInfo1() throws ExecutionException, InterruptedException {
        JSONObject jsonObject = new JSONObject();

        // 异步请求 1
        CompletableFuture<SysUserDTO> userInfo = CompletableFuture.supplyAsync(() -> {
            log.info("1");
            return SysUserDTO.builder().uuid("1").username("sali-1").build();
        });

        // 异步请求 2
        CompletableFuture<SysUserDTO> stateInfo =  CompletableFuture.supplyAsync(() -> {
            log.info("2");
            return SysUserDTO.builder().uuid("2").username("sali-2").build();
        });

        // 异步请求 3
        CompletableFuture<SysUserDTO> signInfo =  CompletableFuture.supplyAsync(() -> {
            log.info("3");
            return SysUserDTO.builder().uuid("3").username("sali-3").build();
        });

        // 合并请求
        jsonObject.put("userInfo", userInfo.get());
        jsonObject.put("stateInfo", stateInfo.get());
        jsonObject.put("signInfo", signInfo.get());
        return  jsonObject;
    }


    @GetMapping("/user/info2")
    public JSONObject getUserInfo2() throws ExecutionException, InterruptedException {
        JSONObject jsonObject = new JSONObject();

        // 异步请求 1
        Future<SysUserDTO> userInfo = executorService.submit(() -> {
            log.info("1");
            return SysUserDTO.builder().uuid("1").username("sali-1").build();
        });

        // 异步请求 2
        Future<SysUserDTO> stateInfo =  executorService.submit(() -> {
            log.info("2");
            return SysUserDTO.builder().uuid("2").username("sali-2").build();
        });

        // 异步请求 3
        Future<SysUserDTO> signInfo =  executorService.submit(() -> {
            log.info("3");
            return SysUserDTO.builder().uuid("3").username("sali-3").build();
        });

        // 合并请求
        jsonObject.put("userInfo", userInfo.get());
        jsonObject.put("stateInfo", stateInfo.get());
        jsonObject.put("signInfo", signInfo.get());
        return  jsonObject;
    }

}
